package com.fmy.jurisdiction.config.security.handel;

import com.fmy.jurisdiction.config.security.SecurityConfig;
import com.fmy.jurisdiction.core.unusual.BizAuthenticationException;
import com.fmy.jurisdiction.core.web.call.ResponseCall;
import com.fmy.jurisdiction.core.web.specs.Response;
import com.fmy.jurisdiction.core.web.specs.ResponseEnum;
import com.fmy.security.cache.Token;
import com.fmy.security.service.LoginHandler;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName LoginHandel
 * @Description TODO 自定义登录成功失败处理
 * @createTime 2019/9/16 17:57
 */
@Component
public class LoginHandel implements LoginHandler<Response> {


    @Override
    public Response resultSuccess(Token token) {
        return ResponseCall.success(token.getToken());
    }

    @Override
    public Response resultFail(AuthenticationException e) {
        if (e instanceof BizAuthenticationException) {
            return ResponseCall.error(ResponseEnum.LOGIN_ERROR, e.getMessage());
        }
        if (e instanceof BadCredentialsException) {
            return ResponseCall.error(ResponseEnum.LOGIN_ERROR, "用户名或密码错误");
        }
        if (e instanceof DisabledException) {
            return ResponseCall.error(ResponseEnum.LOGIN_ERROR, "用户被停用");
        }
        return ResponseCall.error(ResponseEnum.LOGIN_ERROR, e.getMessage());
    }

    @Override
    public void resultPrefix() {
        SecurityConfig.THREADLOCAL_SALT.remove();
    }
}
